package com.tisson.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.tisson.database.FormatUtil;
import com.tisson.database.StatementUtil;
import com.tisson.pojo.AcRight;

public class AcRightDAO {
	private String query;
	private ResultSet rs;

	public AcRight findById(String userId, String doorId) throws SQLException {
		query = "SELECT * FROM ac_right WHERE UserId = '" + userId
				+ "' AND  DoorId = '" + doorId + "'";
		Statement stmt = StatementUtil.getStatement();
		rs = stmt.executeQuery(query);
		AcRight acRight = new AcRight();
		while (rs.next()) {
			acRight.setDoorId(FormatUtil.ConvertUuid(rs.getBytes("DoorId")));
			acRight.setUserId(FormatUtil.ConvertUuid(rs.getBytes("UserId")));
			acRight.setState(rs.getInt("State"));
		}
		rs.close();
		stmt.close();
		return acRight;
	}

	public List findAll() throws SQLException {
		query = "SELECT * FROM ac_right";
		Statement stmt = StatementUtil.getStatement();
		rs = stmt.executeQuery(query);
		List list = new ArrayList();
		while (rs.next()) {
			AcRight acRight = new AcRight();
			acRight.setDoorId(FormatUtil.ConvertUuid(rs.getBytes("DoorId")));
			acRight.setUserId(FormatUtil.ConvertUuid(rs.getBytes("UserId")));
			acRight.setState(rs.getInt("State"));
			list.add(acRight);
		}
		rs.close();
		stmt.close();
		return list;
	}

	public void save(AcRight acRight) {
		query = "insert into ac_right(UserId,DoorId,State) values('"
				+ acRight.getUserId() + "','" + acRight.getDoorId() + "',"
				+ acRight.getState() + ")";
		System.out.println(query);
		try {
			Statement stmt = StatementUtil.getStatement();
			stmt.executeUpdate(query);
			stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void update(AcRight acRight) throws SQLException {
		query = "UPDATE ac_right SET " + "State = " + acRight.getState()
				+ " WHERE UserId = '" + acRight.getUserId()
				+ "' AND DoorId = '" + acRight.getDoorId() + "'";
		Statement stmt = StatementUtil.getStatement();
		stmt.executeUpdate(query);
		stmt.close();
	}

	public void delete(AcRight acRight) throws SQLException {
		query = "DELETE FROM ac_right WHERE UserId = '" + acRight.getUserId()
				+ "' AND DoorId = '" + acRight.getDoorId() + "'";
		Statement stmt = StatementUtil.getStatement();
		stmt.executeUpdate(query);
		stmt.close();
	}

}
